Thread: [BEGINNER] Decimal to Binary Converter help

  1. #1
    Registered User
    Join Date
    Sep 2014
    Posts
    74

    Exclamation [BEGINNER] Decimal to Binary Converter help

    Hello guys,
    I was trying to program an decimal to binary converter (8-bits) in C. I am a complete beginner so I tried to put the 1's and 0's of the binary number as they come without reversing the order for beginning. I have seen example on the internet but didn't understand them so I decided to write it as I understood it. So, I typed the code as shown below:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int number;
        int BitNum[8], x;
        
        printf("Which DECIMAL number you want to convert to BINARY: ");
        scanf("%d", &number);   
          
        
        for(x=0;x<8;x++)
        {
            int modulo=number%2;
    
    
            BitNum[x]=number%2;
            if(modulo==0)
            {
                BitNum[x]==0;
            }
    
            number=(number/2);
            if(number<1)
            {
                break;
            }
    
        }
        for(x=0;x<8;x++)
        {
            printf("%d ",BitNum[x]);
        }
        return(0);
    }

    The problem with the code is that if binary form has 0s in it then program displays a random number instead of a 0. For example if decimal is 7, it should print out 11100000 but it displays only 111(and some stupid numbers insted of 0). I have tried to solve it but failed. Please help me.


    P.S: Any suggestion about my code writing habit is really welcomed . Thanks.
    Last edited by Sankait Laroiya; 09-09-2014 at 07:37 AM.

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    If you compile with warnings, you should see something like the following:

    Code:
    /*
    main.c||In function 'main':|
    main.c|21|warning: statement with no effect|
    ||=== Build finished: 0 errors, 1 warnings ===|
    */
    This is because you accidentally used == (comparison) instead of = (assignment).

    In fact, as you fix up the code, you'll see the "if(modulo==0)" code isn't even necessary.

    The reason you're seeing gibberish sometimes is because you break out of the loop when the number goes below 1, but all the array positions have not necessarily been filled yet. Therefore, when you attempt to print out the numbers at those indices, since they have not been initialized to anything, they contain garbage values.

    Try initializing the entire array to zero. This way, anything not updated in the loop will still have an initial value.

    Code:
    int BitNum[8] = {0};  // initialize all elements to zero
    Then, as mentioned, you want to reverse the array so it prints the bits in the correct order.

    Quote Originally Posted by Sankait Laroiya View Post
    P.S: Any suggestion about my code writing habit is really welcomed . Thanks.
    I am happy to see several things about your code. Neat/consistent indentation, meaningful variable names, proper form of "main()". We don't get enough of that here from new posters. Well done!

  3. #3
    Registered User
    Join Date
    Sep 2014
    Posts
    74
    Quote Originally Posted by Matticus View Post
    If you compile with warnings, you should see something like the following:

    Code:
    /*
    main.c||In function 'main':|
    main.c|21|warning: statement with no effect|
    ||=== Build finished: 0 errors, 1 warnings ===|
    */
    This is because you accidentally used == (comparison) instead of = (assignment).

    In fact, as you fix up the code, you'll see the "if(modulo==0)" code isn't even necessary.

    The reason you're seeing gibberish sometimes is because you break out of the loop when the number goes below 1, but all the array positions have not necessarily been filled yet. Therefore, when you attempt to print out the numbers at those indices, since they have not been initialized to anything, they contain garbage values.

    Try initializing the entire array to zero. This way, anything not updated in the loop will still have an initial value.

    Code:
    int BitNum[8] = {0};  // initialize all elements to zero
    Then, as mentioned, you want to reverse the array so it prints the bits in the correct order.



    I am happy to see several things about your code. Neat/consistent indentation, meaningful variable names, proper form of "main()". We don't get enough of that here from new posters. Well done!


    Well, that was a blazing fast reply. Thanks for the appreciation. I have just modified the code very cleverly and it works now (with reversing order). I kept the modulo thing because its intuitive to me. How about this:

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<math.h>
    
    int main()
    {
        int number;
        int BitNum[8],x;
    
        printf("Which DECIMAL number you want to convert to BINARY: ");
        scanf("%d", &number);
    
        for(x=0;x<8;x++)
        {
            int modulo=number%2;
            BitNum[x]=number%2;
            if(modulo=0)
            {
                BitNum[x]==0;
            }
            number=(number/2);
            if(number<0)
            {
                break;
            }
        }
        for(x=7;x>=0;x--)
        {
            printf("%d",BitNum[x]);
        }
    
        return(0);
    }
    Last edited by Sankait Laroiya; 09-09-2014 at 08:23 AM.

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Well, it appears to work, but not necessarily because it's correct. You have a few mistakes that are canceling each other out, with a net result of making the program give the correct output.

    Let's start with the warnings again:

    Code:
    /*
    main.c||In function 'main':|
    main.c|17|warning: suggest parentheses around assignment used as truth value|
    main.c|19|warning: statement with no effect|
    ||=== Build finished: 0 errors, 2 warnings ===|
    */
    You changed the wrong operator. You had the "modulo == 0" correct (you are making a comparison); it was the "BitNum[x] == 0" that was incorrect (you want to make an assignment).

    Code:
    if(number<0)
    This can never be true in your code, since division with positive numbers (or zero as the numerator) will never yield a negative value. So the "break" is never seen, meaning the program will loop all eight times. Since no loops are skipped, line 16 will ensure that all array indices are given a value (hence bypassing the need to initialize the array, as I originally suggested).

    You're making this more complicated than it has to be. Fun fact: remove everything from your first "for()" loop except for lines 16 and 21, run it, and see what happens. Then try to figure out why that happened. I'd suggest using a pencil and paper to run through the loop "by hand", keeping track of each value each time through the loop. Analyzing code "on paper" like this will help give you a better understanding of what the code is actually doing.

  5. #5
    Registered User
    Join Date
    Sep 2014
    Posts
    74
    Quote Originally Posted by Matticus View Post
    Well, it appears to work, but not necessarily because it's correct. You have a few mistakes that are canceling each other out, with a net result of making the program give the correct output.

    Let's start with the warnings again:

    Code:
    /*
    main.c||In function 'main':|
    main.c|17|warning: suggest parentheses around assignment used as truth value|
    main.c|19|warning: statement with no effect|
    ||=== Build finished: 0 errors, 2 warnings ===|
    */
    You changed the wrong operator. You had the "modulo == 0" correct (you are making a comparison); it was the "BitNum[x] == 0" that was incorrect (you want to make an assignment).

    Code:
    if(number<0)
    This can never be true in your code, since division with positive numbers (or zero as the numerator) will never yield a negative value. So the "break" is never seen, meaning the program will loop all eight times. Since no loops are skipped, line 16 will ensure that all array indices are given a value (hence bypassing the need to initialize the array, as I originally suggested).

    You're making this more complicated than it has to be. Fun fact: remove everything from your first "for()" loop except for lines 16 and 21, run it, and see what happens. Then try to figure out why that happened. I'd suggest using a pencil and paper to run through the loop "by hand", keeping track of each value each time through the loop. Analyzing code "on paper" like this will help give you a better understanding of what the code is actually doing.
    Okay, could you please explain me this:
    When a number is odd; example: number = 9 and we divide it by 2 in the for loop, how come its modulo in the next part of the loop returns a remainder (0 or 1)? What will be 4.5%2?

    Thanks.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Sankait Laroiya
    When a number is odd; example: number = 9 and we divide it by 2 in the for loop, how come its modulo in the next part of the loop returns a remainder (0 or 1)?
    9 / 2 gives you 4, then 4 % 2 gives you 0. As for why: that's how the % operator is supposed to work, i.e., the result of the % operator is the remainder.

    Quote Originally Posted by Sankait Laroiya
    What will be 4.5%2?
    It will be 0.5, except that because the operands of the % operator must be integers, you will get an error instead. If you need to work with floating point, what you can do is to #include <math.h> and use fmod.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Sep 2014
    Posts
    74
    Quote Originally Posted by laserlight View Post
    9 / 2 gives you 4, then 4 % 2 gives you 0. As for why: that's how the % operator is supposed to work, i.e., the result of the % operator is the remainder.


    It will be 0.5, except that because the operands of the % operator must be integers, you will get an error instead. If you need to work with floating point, what you can do is to #include <math.h> and use fmod.
    Thanks, I understood. You mean to say when float is passed to a % it leaves the digits after decimal and simply takes the absolute value, right?
    And Could you also help me with this:
    Code:
    http://cboard.cprogramming.com/c-programming/164203-%5Bbeginner%5D-binary-decimal-converter-help.html#post1211145

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Sankait Laroiya
    You mean to say when float is passed to a % it leaves the digits after decimal and simply takes the absolute value, right?
    No, it will result in an error. If you talk about fmod instead, then the idea is the same as with %, i.e., to compute the remainder. Experiment with fmod.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary to Decimal Converter
    By Rocket Power in forum C Programming
    Replies: 1
    Last Post: 02-26-2013, 05:05 PM
  2. Replies: 7
    Last Post: 12-03-2012, 04:42 AM
  3. Decimal to Hex Converter
    By rocketman03 in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:50 AM
  4. Help with a decimal to binary converter
    By danielerasmus in forum C++ Programming
    Replies: 7
    Last Post: 02-23-2008, 11:37 AM
  5. Decimal to Binary Converter
    By peckitt99 in forum C Programming
    Replies: 16
    Last Post: 10-12-2006, 05:25 AM

Tags for this Thread